#include "widget.h"
#include "./ui_widget.h"


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    // 初始化媒体播放器
    mediaPlayer = new QMediaPlayer(this);
    videoWidget = new QVideoWidget(this);
    mediaPlayer->setVideoOutput(videoWidget);

    QAudioOutput *audioOutput = new QAudioOutput(this);
    mediaPlayer->setAudioOutput(audioOutput);  // Qt6必须设置
    audioOutput->setVolume(50);  // 设置音量(0-100)

    // 设置UI布局
    videoWidget->setMinimumSize(600, 600);
    vbox = new QVBoxLayout(this);

    // 按钮设置
    chooseBtn = new QPushButton("选择视频", this);
    playBtn = new QPushButton(this);
    playBtn->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
    playBtn->setEnabled(false);  // 初始禁用播放按钮

    // 布局管理
    QHBoxLayout *hbox = new QHBoxLayout;
    hbox->addWidget(chooseBtn);
    hbox->addWidget(playBtn);
    vbox->addWidget(videoWidget);
    vbox->addLayout(hbox);
    setLayout(vbox);

    // 信号槽连接
    connect(chooseBtn, &QPushButton::clicked, this, &Widget::chooseVideo);
    connect(playBtn, &QPushButton::clicked, this, &Widget::togglePlayback);
    connect(mediaPlayer, &QMediaPlayer::mediaStatusChanged, this, [this](QMediaPlayer::MediaStatus status) {
        playBtn->setEnabled(status == QMediaPlayer::LoadedMedia);
    });
}

Widget::~Widget()
{
    delete mediaPlayer;
    delete videoWidget;
    delete ui;
}

void Widget::chooseVideo()
{
    // 1. 使用正确的文件对话框方法（getOpenFileName而非getSaveFileName）
    QString filePath = QFileDialog::getOpenFileName(
        this,
        tr("选择视频"),
        QStandardPaths::writableLocation(QStandardPaths::MoviesLocation),
        tr("视频文件 (*.mp4 *.avi *.mov *.wmv *.mkv);;所有文件 (*.*)")
        );

    if (filePath.isEmpty()) {
        qDebug() << "用户取消选择";
        return;
    }

    // 2. 使用Qt6的setSource()替代废弃的setMedia()
    mediaPlayer->setSource(QUrl::fromLocalFile(filePath));

    // 3. 设置视频输出（建议提前设置，此处可省略）
    // mediaPlayer->setVideoOutput(videoWidget);

    // 4. 连接媒体状态变化信号
    connect(mediaPlayer, &QMediaPlayer::mediaStatusChanged, this, [=](QMediaPlayer::MediaStatus status) {
        if (status == QMediaPlayer::LoadedMedia) {
            qDebug() << "视频已加载，分辨率:"
                     << mediaPlayer->videoSink()->videoSize();
            playBtn->setEnabled(true);
        } else if (status == QMediaPlayer::InvalidMedia) {
            qWarning() << "不支持的格式:" << filePath;
        }
    });

    // 5. 错误处理
    connect(mediaPlayer, &QMediaPlayer::errorOccurred, this, [=](QMediaPlayer::Error error, const QString &errorString) {
        qCritical() << "播放错误:" << errorString;
        QMessageBox::warning(this, tr("播放错误"), errorString);
    });
}

void Widget::togglePlayback()
{
    if (isPlaying) {
        mediaPlayer->pause();
        playBtn->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
    } else {
        mediaPlayer->play();
        playBtn->setIcon(style()->standardIcon(QStyle::SP_MediaPause));
    }
    isPlaying = !isPlaying;
}
